package ThirdCommunication;


import java.io.FileWriter;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;


public class MyServer {
    public void createServer(int port) throws IOException {
        //用于监听是否有客户端连接到服务器
        ServerSocket server = new ServerSocket(port);
        //用循环实现服务器对客户端连接请求的持续监听
        while(true){
            //若有客户端连接，则结束accept阻塞状态，返回一个代表客户端的套接字
            Socket client = server.accept();
            //创建ServerThread线程用于处理客户端的请求,启动线程，开始通信
            ServerThread st = new ServerThread(client);
            new Thread(st).start();
            //使用计时器，每隔一段时间就保存一次服务器的数据
            TimerTask ts = new TimerTask(){
                public void run(){
                    //将用户id-pwd写入属性文件
                    Properties pro = new Properties();
                    for(String key:st.getAllUsers().keySet()){
                        pro.setProperty(key,st.getAllUsers().get(key));
                    }
                    try {
                        pro.store(new FileWriter("D:\\java\\idea\\AllProjects\\ChatRoom\\ServerProject\\UsersInfo\\id-pwd.properties"),"update");
                    } catch (Exception e) {
                        System.out.println("数据保存出错");
                    }
                }
            };
            Timer timer = new Timer();
            //延迟1s执行，每隔100s也就是1min就执行一次
            timer.schedule(ts,1000,100000);

        }
    }

    public static void main(String[] args) throws IOException {
        new MyServer().createServer(9090);
    }
}
